import type { CaseReducer, PayloadAction } from '@reduxjs/toolkit'
import { createSlice } from '@reduxjs/toolkit'

import { LoginEnt } from '@/models/LoginEnt'

type LoginEnt2 = LoginEnt & {
  selectedEnt?: LoginEnt
}

const loginEntSlice = createSlice<
  LoginEnt2,
  {
    updateLoginEnt: CaseReducer<LoginEnt, PayloadAction<LoginEnt | undefined>>
    updateSelectedEnt: CaseReducer<
      LoginEnt,
      PayloadAction<LoginEnt | undefined>
    >
  },
  'loginEnt'
>({
  name: 'loginEnt',
  initialState: () => {
    const initialState = new LoginEnt({
      entId: '73b96fb8ccb541e7b2ab9c4ed8db4ee4',
      entName: '嘉兴市质量协会',
      workbenchEntName: '',
      entLogo:
        'https://logibeat-test.oss-cn-hangzhou.aliyuncs.com/images/ercode/ym_logo.png',
      entTypeCode: 'association',
      entAccountId: '0ca1bd85c62448a3a72243b0b18db1e9',
      shamEnt: false,
      directFlag: '2',
      operateEntFlag: 'platform',
      organizationType: '',
      platformName: '嘉兴安全共治平台',
      newBelongIndustry: '',
      serviceTypeValue: '',
      serviceFilingFlag: '',
      memberType: '',
      regionCode: '330402'
    })
    // const loginEntSecret = localStorage.getItem("loginEnt")

    // if (loginEntSecret) {
    //   try {
    //     Object.assign(initialState, JSON.parse(b64_decode(loginEntSecret)))
    //   } catch (e) { }
    // }
    return initialState
  },
  reducers: {
    updateLoginEnt: (state, { payload = new LoginEnt() }) => {
      // localStorage.setItem('loginEnt', b64_encode(JSON.stringify(payload)))

      return { ...payload }
    },
    updateSelectedEnt: (state, { payload }) => {
      return {
        ...state,
        selectedEnt: payload
      }
    }
  }
})
export { loginEntSlice }
